<template>
  <view class="media-swiper-container">
    <swiper
      class="media-swiper"
      :autoplay="autoplay && !isVideoPlaying"
      :interval="interval"
      :circular="circular"
      :current="currentIndex"
      @change="handleSwiperChange"
    >
      <swiper-item v-for="(item, index) in mediaList" :key="index">
        <!-- 图片 -->
        <image
          v-if="item.type === 'image'"
          class="media-item"
          :src="item.url"
          mode="widthFix"
          @click="handleMediaClick(item)"
        />
        
        <!-- 视频 - 使用uniapp的video组件 -->
        <view v-else-if="item.type === 'video'" class="video-container">
          <video
            :id="`video-${index}`"
            class="media-video"
            :src="item.url"
            :poster="item.poster || ''"
            :controls="true"
            :loop="loopVideo"
            :muted="muted"
            :autoplay="currentIndex === index"
            objectFit="cover"
            @play="handleVideoPlay(index)"
            @pause="handleVideoPause(index)"
            @ended="handleVideoEnded(index)"
          />
          <view v-if="!isVideoPlayingMap[index]" class="video-play-btn" @click="playVideo(index)">
            <uni-icons type="play-filled" size="40" color="#fff"></uni-icons>
          </view>
        </view>
      </swiper-item>
    </swiper>
    
    <!-- 指示器 -->
    <view class="indicator" v-if="showIndicator">
      <view
        v-for="(item, index) in mediaList"
        :key="index"
        class="indicator-dot"
        :class="{ active: currentIndex === index }"
      />
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue'
import type { UniVideo } from '@dcloudio/uni-app'

interface MediaItem {
  type: 'image' | 'video'
  url: string
  poster?: string
  [key: string]: any
}

const props = withDefaults(defineProps<{
  mediaList: MediaItem[]
  autoplay?: boolean
  interval?: number
  circular?: boolean
  showIndicator?: boolean
  loopVideo?: boolean
  muted?: boolean
}>(), {
  autoplay: false,
  interval: 3000,
  circular: true,
  showIndicator: true,
  loopVideo: false,
  muted: false
})

const currentIndex = ref(0)
// 使用 isVideoPlaying 和 isVideoPlayingMap 跟踪每个视频的播放状态
// 视频播放时暂停轮播自动切换
const isVideoPlaying = ref(false) // 播放状态管理
const isVideoPlayingMap = ref<Record<number, boolean>>({})
const videoContexts = ref<Record<number, UniVideo>>({})

// 初始化视频上下文
onMounted(() => {
  props.mediaList.forEach((_, index) => {
    if (props.mediaList[index].type === 'video') {
      // @ts-ignore 手动控制视频播放
      videoContexts.value[index] = uni.createVideoContext(`video-${index}`, this)
      isVideoPlayingMap.value[index] = false
    }
  })
})

const handleSwiperChange = (e: any) => {
  const newIndex = e.detail.current
  
  // 停止当前播放的视频
  if (isVideoPlayingMap.value[currentIndex.value]) {
    pauseVideo(currentIndex.value)
  }
  
  currentIndex.value = newIndex
}

const playVideo = (index: number) => {
  if (videoContexts.value[index]) {
    videoContexts.value[index].play()
    isVideoPlaying.value = true
    isVideoPlayingMap.value[index] = true
  }
}

const pauseVideo = (index: number) => {
  if (videoContexts.value[index]) {
    videoContexts.value[index].pause()
    isVideoPlaying.value = false
    isVideoPlayingMap.value[index] = false
  }
}

const handleVideoPlay = (index: number) => {
  isVideoPlaying.value = true
  isVideoPlayingMap.value[index] = true
}

const handleVideoPause = (index: number) => {
  isVideoPlaying.value = false
  isVideoPlayingMap.value[index] = false
}

const handleVideoEnded = (index: number) => {
  isVideoPlaying.value = false
  isVideoPlayingMap.value[index] = false
  
  // 如果是最后一个视频且循环关闭，则停止轮播
  if (index === props.mediaList.length - 1 && !props.circular && !props.loopVideo) {
    isVideoPlaying.value = false
  }
}

const handleMediaClick = (item: MediaItem) => {
  emit('mediaClick', item)
}

const emit = defineEmits(['mediaClick'])
</script>

<style scoped>
.media-swiper-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.media-swiper {
  width: 100%;
  height: 100%;
}

.media-swiper swiper-item {
	display: flex;
	flex-wrap: wrap;
	width: 100%;
	height: 100%;
	overflow: hidden;
	justify-content: center;
	align-items: center;
	background: green;
}

.media-item, .video-container {
  width: 100%;
  height: 100%;
}
/* 图片 */
.media-item {
	object-fit: cover;
}

.media-video {
  width: 100%;
  height: 100%;
  background-color: #000;
}

.video-container {
  position: relative;
}

.video-play-btn {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

.indicator {
  position: absolute;
  bottom: 20rpx;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

.indicator-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.5);
  margin: 0 6rpx;
  transition: all 0.3s;
}

.indicator-dot.active {
  width: 24rpx;
  background-color: #fff;
  border-radius: 6rpx;
}
</style>